package com.dtlaya.allutils.dcmFileUpload.service;

import com.dtlaya.allutils.dcmFileUpload.config.DicomStorageProperties;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.Tag;
import org.dcm4che3.io.DicomInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Service
public class DicomParserService {

    private final DicomStorageProperties storageProperties;

    @Autowired
    public DicomParserService(DicomStorageProperties storageProperties) {
        this.storageProperties = storageProperties;
    }

    /**
     * 解析 DICOM 文件并生成存储路径
     * @param dicomFile DICOM 文件
     * @return 生成的完整存储路径
     * @throws IOException 文件读取异常
     */
    public Path parseAndGeneratePath(MultipartFile dicomFile) throws IOException {
        // 解析 DICOM 文件元数据
        Attributes attributes = parseDicomAttributes(dicomFile);
        
        // 提取需要的标签值
        Map<String, String> tagValues = new HashMap<>();
        tagValues.put("StudyDate", getTagValue(attributes, Tag.StudyDate));
        tagValues.put("StudyInstanceUID", getTagValue(attributes, Tag.StudyInstanceUID));
        tagValues.put("SeriesInstanceUID", getTagValue(attributes, Tag.SeriesInstanceUID));
        tagValues.put("SOPIntanceUID", getTagValue(attributes, Tag.SOPInstanceUID));
        // 生成相对路径
        String relativePath = generateRelativePath(tagValues);

        // 构建完整路径
        return Paths.get(storageProperties.getBasePath(), relativePath);
    }

    /**
     * 解析 DICOM 文件属性
     * @param dicomFile DICOM 文件
     * @return DICOM 属性集合
     * @throws IOException 文件读取异常
     */
    private Attributes parseDicomAttributes(MultipartFile dicomFile) throws IOException {
        try (DicomInputStream dis = new DicomInputStream(dicomFile.getInputStream())) {
            return dis.readDataset(-1, -1); // 读取所有元数据
        }
    }

    /**
     * 获取标签值并处理空值
     * @param attributes DICOM 属性
     * @param tag 标签 ID
     * @return 标签值字符串
     */
    private String getTagValue(Attributes attributes, int tag) {
        String value = attributes.getString(tag);
        if (value == null || value.trim().isEmpty()) {
            return "UNKNOWN"; // 空值处理
        }
        return sanitizePathComponent(value);
    }

    /**
     * 清理路径组件，移除无效字符
     * @param component 路径组件
     * @return 安全路径组件
     */
    private String sanitizePathComponent(String component) {
        // 移除非法字符（Windows 和 Linux 都不允许的字符）
        return component.replaceAll("[\\\\/:*?\"<>|]", "_")
                        .replaceAll("\\s+", " ")
                        .trim();
    }

    /**
     * 根据路径模式生成相对路径
     * @param tagValues 标签值映射
     * @return 生成的相对路径
     */
    private String generateRelativePath(Map<String, String> tagValues) {
        String pattern = storageProperties.getPathPattern();
        
        // 替换模式中的占位符
        for (Map.Entry<String, String> entry : tagValues.entrySet()) {
            String placeholder = entry.getKey() ;
            pattern = pattern.replaceAll(placeholder,entry.getValue());
        }
        
        // 标准化路径
        return pattern.replace("\\", "/")
                      .replaceAll("/+", "/");
    }
}